package com.time.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.time.domain.News;
import com.time.domain.Product;
import com.time.domain.ProductCategory;
import com.time.service.NewsService;
import com.time.service.ProductCategoryService;
import com.time.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author 张龙佼
 * @Description 主类 controller
 * @since 2020-10-19
 */

@Controller
public class IndexController {

    @Autowired
    private NewsService newsService;
    @Autowired
    private ProductService productService;
    @Autowired
    private ProductCategoryService productCategoryService;

    /**
     * @param model       封装分页新闻和商品数据和总页数
     * @param session     将商品分类数据封装至session，以便任何位置都能访问
     * @param currentPage 当前页，默认第1页
     * @param pageSize    每页显示数，默认每页8条
     * @return 请求转发至前台主页
     * @Description 跳转至前台主页
     */
    @RequestMapping("/index")
    public String frontIndex(Model model, HttpSession session,
                             @RequestParam(value = "currentPage", defaultValue = "1") Long currentPage,
                             @RequestParam(value = "pageSize", defaultValue = "8") Long pageSize) {
        // 分页获取新闻信息并封装
        Page<News> pageNews = new Page<>(1, 7);
        Page<News> newsPage = newsService.page(pageNews);
        model.addAttribute("newsPage", newsPage);

        // 分页获取商品信息并封装
        Page<Product> page = new Page<>(currentPage, pageSize);
        Page<Product> productPage = productService.page(page);
        model.addAttribute("productPage", productPage);
        model.addAttribute("totalPage", productPage.getPages());

        // 分页获取商品分类信息并封装至session
        List<ProductCategory> productCategories = productCategoryService.productCategories();
        session.setAttribute(ProductCategory.PRODUCT_CATEGORY_IN_SESSION, productCategories);

        return "index";
    }

    /**
     * @return 请求转发至后台主页
     * @Description 跳转后台主页
     */
    @RequestMapping("/manage/index")
    public String manageIndex() {

        return "/manage/index";
    }
}
